package com.wlts.wzy.KSGoodsModule.util;

import com.alibaba.fastjson.JSON;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.request.KsMerchantItemCategoryRequest;
import com.kuaishou.merchant.open.api.response.KsMerchantItemCategoryResponse;
import com.kuaishou.merchant.open.api.response.view.item.MerchantItemCategoryView;
import com.wlts.wzy.KSGoodsModule.entity.KsCategory;
import com.wlts.wzy.KSGoodsModule.service.IKsCategoryService;
import com.wlts.wzy.configBean.KsConfig.KsConfigTemp;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.CopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class KsGoodsUpdate {
    @Autowired
    private IKsCategoryService ksCategoryService;


    //    @Scheduled(fixedDelay = 120 * 1000)
   // @PostConstruct
    public void updateKsCategory() throws KsMerchantApiException {

        KsMerchantItemCategoryRequest ksMerchantItemCategoryRequest = new KsMerchantItemCategoryRequest();
        ksMerchantItemCategoryRequest.setAccessToken(KsConfigTemp.accessToken);
        KsMerchantItemCategoryResponse ksMerchantItemCategoryResponse = KsConfigTemp.tokenKsMerchantClient.execute(ksMerchantItemCategoryRequest);

   //  System.out.println(JSON.toJSONString(ksMerchantItemCategoryResponse));

        List<MerchantItemCategoryView> categoryViewList = ksMerchantItemCategoryResponse.getKsMerchantItemCategoryData();

        List<KsCategory> ksCategoryList = categoryViewList.stream().map(categoryView -> {
            KsCategory ksCategory = new KsCategory();

            CopyUtils.copyProperties(categoryView, ksCategory);
            MyLambdaQueryWrapper<KsCategory> wrapper = new MyLambdaQueryWrapper<>(ksCategory);
            KsCategory category = ksCategoryService.getOne(wrapper);
            if(category!=null){
                return category;
            }
            return ksCategory;
        }).filter(a->a.getId()==null).collect(Collectors.toList());

        ksCategoryService.saveBatch(ksCategoryList);
    }

}
